const { DB } = require("../config")

/**
 *
 * @param {*} tableName 需要查询的表的名称
 * @returns
 */
async function getLength(tableName, where) {
	const args = []
	let sql = ""
	for (let i = 0; i < where.length; i++) {
		const item = where[i]
		if (item.val && item.val !== "0") {
			sql += ` ${item.key}=? AND`
			args.push(item.val)
		}
	}

	let resSql = ""
	if (sql.length > 0) {
		resSql = " WHERE " + sql.slice(0, -3)
	}

	try {
		const [rows] = await DB.execute(
			"SELECT COUNT(id) AS numb FROM " + tableName + resSql,
			args
		)
		return rows[0].numb
	} catch (error) {
		console.error("error", error)
		throw error
	}
}

module.exports = {
	getLength
}
